var serverDomain = 'trace.shujet.com';

var title = document.title;

var refurl = "";

var currentUrl = window.location.href;

var SESSION_KEY = "tsessionId";

var traceId = "";

var isVue = false;


/**
 * 使用方法 传统项目
 * <script type="text/javascript" src="http://trace.shujet.com/trace.js"></script>
 * <script>
 *(function() {
 *       this.trace('66666'); //需要传入参数 系统ID
  *  })();
 </script>

    对于vuejs项目:
    1. 首先在 index.html中引入

    <script type="text/javascript" src="http://trace.shujet.com/trace.js"></script>

    router.beforeEach((to, from, next) => {
        2.在 main.js中的路由前置拦截中加入
        traceVue('555555', from.fullPath, to.fullPath);
    });

 */

function traceVue(sysId, from, to) {
    currentUrl = to;
    refurl = from;
    isVue = true;
    trace(sysId);
}


function trace(sysId) {

    if (!refurl || refurl === '' || refurl == null) {
        if (document.referrer.length > 0) {
            refurl = document.referrer;
        }
        try {
            if (ref.length == 0 && opener.location.href.length > 0) {
                refurl = opener.location.href;
            }
        } catch (e) {
        }
    }

    var machineId = getCookieValue('machineId');
    if (machineId.length === 0) {
        machineId = generateMachineId();
    }
    var sessionId = '';

    if (window.sessionStorage) {
        sessionId = sessionStorage.getItem(SESSION_KEY);
        if (sessionId == null) {
            sessionId = generateSessionStoragy();
        }
    }
    else {
        sessionId = getCookieValue(SESSION_KEY);
        if (sessionId.length === 0) {
            sessionId = generateCookieSessionId();
        }
    }
    var userId = getCookieValue('userId');
    this.sendTrace(machineId, sessionId, userId, sysId, title, refurl, currentUrl);
}

/**
 * 页面离开时触发
 * @param ev
 */
window.onbeforeunload = function (ev) {
    var xhr = ajaxFunction();
    var url = "http://" + serverDomain + "/trace/record/leave?id=" + traceId;
    xhr.open("GET", url, true);
    xhr.send();
}

/**
 * 发送记录到服务器
 * @param userId
 * @param sysName
 */
function sendTrace(machineId, sessionId, userId, sysId, title, refurl, currentUrl) {

    if (sessionId == null) {
        sessionId = getCookieValue('JSESSIONID');
    }
    var xhr = ajaxFunction();
    var url = "http://" + serverDomain + "/trace/record/add?machineId=" + machineId + "&sessionId=" + sessionId +
        "&userId=" + userId +
        "&sysId=" + sysId + "&pageTitle=" + title + "&refererUrl=" + refurl + "&url=" + currentUrl+"&isVue="+isVue;
    url = encodeURI(url);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var responseText = xhr.responseText;
            var obj = JSON.parse(responseText);
            traceId = obj.data;
        }
    };
    xhr.open("POST", url, true);
    xhr.send();
}

function ajaxFunction() {
    var xmlHttp;
    try { // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        try {// Internet Explorer
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
            }
        }
    }
    return xmlHttp;
}

/**
 * 生成SessionStoragy型SessionId
 * @returns {*}
 */
function generateSessionStoragy() {
    var sessionId = guid();
    try {
        sessionStorage.setItem(SESSION_KEY, sessionId);
    } catch (error) {
        return "";
    }
    return sessionStorage.getItem(SESSION_KEY);
}

/**
 * 生成Cookie型的SessionId
 * @returns {*}
 */
function generateCookieSessionId() {
    var sessionId = guid();
    this.addCookie(SESSION_KEY, sessionId, -1);
    return sessionId;
}

/**
 * 生成机器Id
 * @returns {string}
 */
function generateMachineId() {
    var machineId = 'trace' + guid();
    this.addCookie('machineId', machineId, '');
    return machineId;
}


/**
 * 获取Cookie中的值
 * @param name
 * @returns {string}
 */
function getCookieValue(name) {
    var strcookie = document.cookie;
    var arrcookie = strcookie.split("; ");
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] === name) {
            return arr[1];
        }
    }
    return "";
}

/**
 * 添加Cookie
 * @param objName
 * @param objValue
 * @param objDays
 */
function addCookie(objName, objValue, objDays) {
    var str = objName + "=" + escape(objValue);
    if (objDays > 0) {
        var date = new Date();
        var ms = objDays * 24 * 3600 * 1000;
        date.setTime(date.getTime() + ms);
        str += "; expires=" + date.toGMTString();
    }
    if (objDays === -1) {
        str += "; expires=" + -1;
    }
    if (objDays === '') {
        str += "; expires=Fri, 31 Dec 9999 23:59:59 GMT";
    }
    str += "; path=/";
    document.cookie = str;
};


function guid() {
    return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
